
package net.atremmedia.gwt.actionjava.examples.basics.samples;

import net.atremmedia.gwt.actionjava.examples.AJExample;
import net.atremmedia.gwt.actionjava.examples.frame.AJExampleOverview;
import actionjava.display.Graphics;
import actionjava.display.Shape;
import actionjava.events.tick.TickEvent;

public class Friction1 extends AJExample
{
	public static final String NAME = "Friction 1";
	public static final String DESCRIPTION = "Description";
	public static final String EXAMPLE_SRC = "https://code.google.com/p/gwt-actionjava/source/browse/trunk/aj-examples/aj-examples-basics/src/main/java/net/atremmedia/gwt/actionjava/examples/basics/samples/Friction1.java";

	private Shape ball;
	private double vx = 0;
	private double vy = 0;
	private double radius = 50;
	private double friction = .1;

	public Friction1(AJExampleOverview base)
	{
		super(NAME, DESCRIPTION, EXAMPLE_SRC, base);
	}

	private void initialize()
	{
		vx = 0;
		vy = 0;
	}

	@Override
	public void run()
	{
		initialize();
		createBall();

		ball.setX(getWidth() / 2);
		ball.setY(getHeight() / 2);
		vx = Math.random() * 10 - 5;
		vy = Math.random() * 10 - 5;
		addChild(ball);
	}

	private Shape createBall()
	{
		ball = new Shape();

		Graphics graphs = ball.getGraphics();
		graphs.beginFill(getRandomColor());
		graphs.drawCircle(0, 0, radius);
		graphs.endFill();

		return ball;
	}

	@Override
	public void onRenderTick(TickEvent event)
	{
		double speed = Math.sqrt(vx * vx + vy * vy);
		double angle = Math.atan2(vy, vx);
		if(speed > friction) {
			speed -= friction;
		} else {
			speed = 0;
		}
		vx = Math.cos(angle) * speed;
		vy = Math.sin(angle) * speed;
		ball.addX(vx);
		ball.addY(vy);
	}
}
